/**
 * This file is a part of Angry IP Scanner source code,
 * see http://www.angryip.org/ for more information.
 * Licensed under GPLv2.
 */
package net.azib.ipscan.exporters;

import net.azib.ipscan.config.Version;

import javax.inject.Inject;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * XMLExporter
 *
 * @author Anton Keks
 */
public class XMLExporter extends AbstractExporter {
	static final String ENCODING = "UTF-8";

	@Inject public XMLExporter() {}

	private int ipFetcherIndex;
	private String[] fetcherNames;
	
	public String getId() {
		return "exporter.xml";
	}

	public String getFilenameExtension() {
		return "xml";
	}

	@Override
	public void shouldAppendTo(File file) {
		// TODO: allow appending: use RandomAccessFile here to remove the closing tag before appending
		throw new ExporterException("xml.noAppend");
	}

	@Override
	public void start(OutputStream outputStream, String feederInfo) throws IOException {
		output = new PrintWriter(new OutputStreamWriter(outputStream, ENCODING));
		output.println("<?xml version=\"1.0\" encoding=\"" + ENCODING + "\" standalone=\"yes\"?>");
		output.println("<!-- This file has been generated by " + Version.getFullName() + " -->");
		output.println("<!-- Visit the website at " + Version.WEBSITE + " -->");
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		output.println("<scanning_report time=\"" + sdf.format(new Date()) + "\">");
		
		// this is a hack to extract feeder name from the feederInfo
		// this may not work with some non-standard feeders
		int colonPos = feederInfo.indexOf(':');
		String feederName = null;
		if (colonPos >= 0) {
			feederName = feederInfo.substring(0, colonPos);
			feederInfo = feederInfo.substring(colonPos + 1);
		}
		output.print("\t<feeder" + (feederName != null ? " name=\"" + feederName.trim() +"\"" : "") + ">");
		output.print("<![CDATA[" + feederInfo.trim() + "]]>");
		output.println("</feeder>");
		
		output.println("\t<hosts>");
	}

	@Override
	public void end() throws IOException {
		output.println("\t</hosts>");
		output.println("</scanning_report>");
		if (output.checkError()) {
			throw new IOException();
		}
	}

	public void setFetchers(String[] fetcherNames) throws IOException {
		ipFetcherIndex = IPListExporter.findFetcherById("fetcher.ip", fetcherNames);
		this.fetcherNames = fetcherNames;
	}

	public void nextAddressResults(Object[] results) throws IOException {
		output.println("\t\t<host address=\"" + results[ipFetcherIndex] + "\">");
		
		for (int i = 0; i < results.length; i++) {
			if (results[i] != null) {
				output.println("\t\t\t<result name=\"" + fetcherNames[i] + "\"><![CDATA[" + results[i] + "]]></result>");
			}
		}
		
		output.println("\t\t</host>");
	}
}
